package com.example.controller;

import cn.hutool.core.util.StrUtil;
import com.graduation.dto.AttackTaskAssignDO;
import com.graduation.dto.AttackTaskDO;
import com.graduation.mapper.AttackTaskAssignMapper;
import com.graduation.mapper.AttackTaskMapper;
import com.graduation.mapper.EmployeeMapper;
import com.graduation.mapper.OrganizationMapper;
import com.graduation.pojo.*;
import com.graduation.pojo.EmployeeQuery;
import com.graduation.pojo.OrganizationQuery;
import com.graduation.vo.AttackTaskVO;
import com.graduation.vo.EmployeeVO;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;

@Controller
@WebException
@RequestMapping("/attack-task")
public class AttackTaskController extends BaseController<AttackTaskDO, AttackTaskVO> {

    @Resource
    private AttackTaskMapper attackTaskMapper;
    @Resource
    private OrganizationMapper organizationMapper;
    @Resource
    private EmployeeMapper employeeMapper;
    @Resource
    private AttackTaskAssignMapper taskAssignMapper;

    @ResponseBody
    @GetMapping("/get")
        public WebResult<AttackTaskVO> get(Integer id) {
        return new WebResult<>(getVoByDo(attackTaskMapper.selectById(id), AttackTaskVO.class));
    }

    @ResponseBody
    @PostMapping("/page")
    public WebResult<PageResult<AttackTaskVO>> page(AttackTaskQuery query) {
        PageResult<AttackTaskVO> result = new PageResult<>();
        result.setRowCount(attackTaskMapper.selectCount(query));
        result.setPageCount((result.getRowCount() - 1) / query.getPageSize() + 1);
        if (query.getPageNum() > result.getPageCount()) {
            query.setPageNum(result.getPageCount());
        }
        result.setPageNum(query.getPageNum());
        // 设置分页查询偏移量
        query.setLimit((query.getPageNum() - 1) * query.getPageSize());
        result.setEntityList(attackTaskMapper.selectList(query).stream()
                .map(e -> getVoByDo(e, AttackTaskVO.class))
                .collect(Collectors.toList()));
        return new WebResult<>(result);
    }

    @ResponseBody
    @PostMapping("/operate")
    public WebResult<?> operate(HttpServletRequest servletRequest, AttackTaskRequest request) {
        if (StrUtil.isBlank(request.getJoinedTesters())) {
            return WebResult.failed("请选择测试人员");
        }
        request.setJoinedTesters(request.getJoinedTesters() + ",");
        AttackTaskDO attackTaskDO = getDoByRequest(request, AttackTaskDO.class);
        if (Objects.isNull(attackTaskDO.getId())) {
            attackTaskDO.setCreateTime(LocalDateTime.now());
            attackTaskDO.setUpdateTime(LocalDateTime.now());
            attackTaskDO.setTaskStatus("未开始");
            attackTaskMapper.insert(attackTaskDO);
        } else {
            attackTaskDO.setUpdateTime(LocalDateTime.now());
            attackTaskMapper.updateById(attackTaskDO);
        }
        return WebResult.success();
    }

    @ResponseBody
    @PostMapping("/start")
    public WebResult<?> start(Integer id) {
        AttackTaskDO task = attackTaskMapper.selectById(id);
//        if (!"未开始".equals(task.getTaskStatus())) {
//            return WebResult.failed("任务" + task.getTaskStatus() + "，不能开始");
//        }
        task.setTaskStatus("进行中");
        attackTaskMapper.updateById(task);
        return WebResult.success();
    }

    @ResponseBody
    @PostMapping("/end")
    public WebResult<?> end(Integer id) {
        AttackTaskDO task = attackTaskMapper.selectById(id);
//        if (!"进行中".equals(task.getTaskStatus())) {
//            return WebResult.failed("任务" + task.getTaskStatus() + "，不能结束");
//        }
        task.setTaskStatus("已完成");
        attackTaskMapper.updateById(task);
        return WebResult.success();
    }

    @ResponseBody
    @DeleteMapping("/delete")
    public WebResult<?> delete(Integer id) {
        attackTaskMapper.deleteById(id);
        return WebResult.success();
    }

    @RequestMapping("/to-attack-task")
    public String toAttackTask() {
        return "attack/attackTaskAdmin";
    }

    @RequestMapping("/to-operate")
    public String toOperate(Model model, Integer id) {
        model.addAttribute("id", id);
        model.addAttribute("task", Objects.isNull(id)? new AttackTaskDO(): attackTaskMapper.selectById(id));
        model.addAttribute("organizationList", organizationMapper.selectList(new OrganizationQuery()));
        EmployeeQuery employeeQuery = new EmployeeQuery();
        employeeQuery.setRole("tester");
        model.addAttribute("testerList", employeeMapper.selectList(employeeQuery));
        model.addAttribute("organizationList", organizationMapper.selectList(new OrganizationQuery()));
        return "attack/operateAttackTask";
    }

    @RequestMapping("/to-assign")
    public String toAssign(Model model, Integer id) {
        model.addAttribute("id", id);
        AttackTaskDO task = attackTaskMapper.selectById(id);
        model.addAttribute("task", task);
        if ("已完成".equals(task.getTaskStatus())) {
            model.addAttribute("errorInfo", "任务已完成，不能指派");
            return "base/error";
        }
        model.addAttribute("testerList", Arrays.stream(task.getJoinedTesters().split(","))
                .filter(StrUtil::isNotBlank)
                .map(e -> {
                    EmployeeVO employee = new EmployeeVO();
                    employee.setName(e);
                    return employee;
                }).collect(Collectors.toList()));
        return "attack/assignAttackTask";
    }

    @ResponseBody
    @PostMapping("/assign")
    public WebResult<?> assign(AttackTaskRequest request) {
        if (StrUtil.isBlank(request.getJoinedTesters())) {
            return WebResult.failed("请选择指派人员");
        }
        String[] testers = request.getJoinedTesters().split(",");
        for (String tester: testers) {
            AttackTaskAssignDO taskAssign = new AttackTaskAssignDO();
            taskAssign.setTaskId(request.getId());
            taskAssign.setCompleteStatus("待接受");
            taskAssign.setExecutor(tester);
            taskAssignMapper.insert(taskAssign);
        }
        return WebResult.success();
    }
}
